﻿namespace SAD.ClientLogic
{
    using System;
    using System.ServiceModel;
    using SAD.Common;
    using System.Collections.Generic;
    using SAD.Common.Helper;
    using SAD.Common.Models;
    using SAD.ShowNodeClientLib;

    public class MainActivator
    {
        internal int ReNum = 10;

        public bool Prepared { get; private set; }

        public int InfoMaxNumber
        {
            get
            {
                if (m_MaxInfoNumber == -1)
                {
                    if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["InfoMaxNumber"]))
                    {
                        m_MaxInfoNumber = int.Parse(System.Configuration.ConfigurationManager.AppSettings["InfoMaxNumber"]);
                    }
                    else
                    {
                        m_MaxInfoNumber = 300;
                    }
                }
                return m_MaxInfoNumber;
            }
        }
        private int m_MaxInfoNumber = -1;

        public int InfoPageSize
        {
            get
            {
                if (m_InfoPageSize == -1)
                {
                    if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["InfoPageSize"]))
                    {
                        m_InfoPageSize = int.Parse(System.Configuration.ConfigurationManager.AppSettings["InfoPageSize"]);
                    }
                    else
                    {
                        m_InfoPageSize = 26;
                    }
                }
                return m_InfoPageSize;
            }
        }
        private int m_InfoPageSize = -1;

        public int InfoAutoScrollTimeSpan
        {
            get
            {
                if (m_InfoAutoScrollTimeSpan == -1)
                {
                    if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["InfoAutoScrollTimeSpan"]))
                    {
                        int msAutoScrollTimeSpan = int.Parse(System.Configuration.ConfigurationManager.AppSettings["InfoAutoScrollTimeSpan"]);
                        m_InfoAutoScrollTimeSpan = msAutoScrollTimeSpan * 1000;
                    }
                    else
                    {
                        m_InfoAutoScrollTimeSpan = 1000;
                    }
                }
                return m_InfoAutoScrollTimeSpan;
            }
        }
        private int m_InfoAutoScrollTimeSpan = -1;

        public SAD.Common.Models.ShowNode_Data ShowNodeData { get; internal set; }

        public Exception LastException { get; private set; }

        public InfoCategory_Data[] InfoCategorys { get; private set; }

        public Dictionary<int, Info_Data[]> InfosByCategoryID { get; private set; }

        private SAD.Common.Contracts.DataCenter.IShowNodeManager ShowNodeManager
        {
            get
            {
                if (m_ShowNodeManager == null)
                {
                    m_ShowNodeManager = System.ServiceModel.ChannelFactory<SAD.Common.Contracts.DataCenter.IShowNodeManager>.CreateChannel(new System.ServiceModel.BasicHttpBinding(), new System.ServiceModel.EndpointAddress(string.Format("{0}/ShowNodeManager", EnvironmentVariables.DataServerUri)));
                }
                return m_ShowNodeManager;
            }
        }
        private SAD.Common.Contracts.DataCenter.IShowNodeManager m_ShowNodeManager;

        private SAD.Common.Contracts.DataCenter.IInfoCategoryManager InfoCategoryManager
        {
            get
            {
                if (m_InfoCategoryManager == null)
                {
                    m_InfoCategoryManager = System.ServiceModel.ChannelFactory<SAD.Common.Contracts.DataCenter.IInfoCategoryManager>.CreateChannel(new System.ServiceModel.BasicHttpBinding(), new System.ServiceModel.EndpointAddress(string.Format("{0}/InfoCategoryManager", EnvironmentVariables.DataServerUri)));
                }
                return m_InfoCategoryManager;
            }
        }
        private SAD.Common.Contracts.DataCenter.IInfoCategoryManager m_InfoCategoryManager;

        internal SAD.Common.Contracts.DataCenter.IInfoManager InfoManager
        {
            get
            {
                if (m_InfoManager == null)
                {
                    m_InfoManager = System.ServiceModel.ChannelFactory<SAD.Common.Contracts.DataCenter.IInfoManager>.CreateChannel(new System.ServiceModel.BasicHttpBinding(), new System.ServiceModel.EndpointAddress(string.Format("{0}/InfoManager", EnvironmentVariables.DataServerUri)));
                }
                return m_InfoManager;
            }
        }
        private SAD.Common.Contracts.DataCenter.IInfoManager m_InfoManager;

        public int debug_RecvCount { get; set; }

        #region Instance
        /// <summary>
        /// 
        /// </summary>
        public static MainActivator Current
        {
            get
            {
                return m_Current;
            }
        }
        private static MainActivator m_Current = new MainActivator();
        #endregion

        private MainActivator()
        {

        }

        public bool Start()
        {
            if (!Prepared)
            {
                //
                int num = 0;

                //
                this.ShowNodeData = new SAD.Common.Models.ShowNode_Data();
                this.InfosByCategoryID = new Dictionary<int, Info_Data[]>();

                //读取ShowNodeMark
                if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["ShowNodeMark"]))
                {
                    this.ShowNodeData.Mark = System.Configuration.ConfigurationManager.AppSettings["ShowNodeMark"];
                }
                else
                {
                    LastException = new Exception("启动失败，ShowNodeMark 没有配置!");
                    return false;
                }

                //取自身的IP和服务端口
                string showNodeIP = null;
                int shwoNodePort = 0;
                if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["ShowNodeIP"]))
                {
                    showNodeIP = System.Configuration.ConfigurationManager.AppSettings["ShowNodeIP"];
                }
                else
                {
                    num = 0;
                    while (true)
                    {
                        try
                        {
                            showNodeIP = MainActivator.Current.ShowNodeManager.GetShowNodeIP();
                            break;
                        }
                        catch (Exception ex)
                        {
                            num++;
                            if (num > MainActivator.Current.ReNum)
                            {
                                LastException = new Exception("启动失败，获取自身服务信息失败!");
                                return false;
                            }
                            System.Threading.Thread.Sleep(100);
                        }
                    }
                }
                if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["ShowNodePort"]))
                {
                    shwoNodePort = int.Parse((System.Configuration.ConfigurationManager.AppSettings["ShowNodePort"]));
                }
                else
                {
                    shwoNodePort = 80;
                }
                MainActivator.Current.ShowNodeData.HostUri = string.Format("{0}:{1}", showNodeIP, shwoNodePort.ToString());

                //注册上线
                num = 0;
                while (true)
                {
                    try
                    {
                        this.ShowNodeData = ShowNodeManager.SetOnline(MainActivator.Current.ShowNodeData.Mark, MainActivator.Current.ShowNodeData.HostUri);
                        break;
                    }
                    catch (Exception ex)
                    {
                        num++;
                        if (num > this.ReNum)
                        {
                            LastException = new Exception("启动失败，注册上线失败!");
                            return false;
                        }
                        System.Threading.Thread.Sleep(100);
                    }
                }

                //读取分类数据
                num = 0;
                while (true)
                {
                    try
                    {
                        this.InfoCategorys = InfoCategoryManager.GetInfoCategorys(MainActivator.Current.ShowNodeData.ID);
                        break;
                    }
                    catch (Exception ex)
                    {
                        num++;
                        if (num > this.ReNum)
                        {
                            LastException = new Exception("启动失败，读取信息分类数据失败!");
                            return false;
                        }
                        System.Threading.Thread.Sleep(100);
                    }
                }

                //读取初始info数据
                Info_Data[] infos = null;
                foreach (InfoCategory_Data categroy in this.InfoCategorys)
                {
                    num = 0;
                    while (true)
                    {
                        try
                        {
                            if (InfosByCategoryID.ContainsKey(categroy.ID))
                            {
                                continue;
                            }
                            infos = MainActivator.Current.InfoManager.GetInfos(MainActivator.Current.ShowNodeData.ID, categroy.ID, DateTime.MinValue, this.InfoMaxNumber);
                            InfosByCategoryID.Add(categroy.ID, infos);
                            foreach (var r in infos)
                            {
                                InfoReceiverManager.Instance.UpdateLastInfoTime(r.AddTime);
                            }
                            break;
                        }
                        catch (Exception ex)
                        {
                            num++;
                            if (num > this.ReNum)
                            {
                                LastException = new Exception("启动失败，读取信息分类数据失败!");
                                return false;
                            }
                            System.Threading.Thread.Sleep(100);
                        }
                    }
                }

                InfoReceiverManager.Instance.Start();

                //准备就绪
                Prepared = true;
                return true;
            }

            return false;
        }

        public bool Stop()
        {
            //
            this.InfosByCategoryID.Clear();
            this.InfosByCategoryID = null;
            this.InfoCategorys = null;

            //
            try
            {
                ShowNodeManager.SetOffline(this.ShowNodeData.Mark);
            }
            catch (Exception ex)
            {
                LastException = new Exception("停止失败，设置下线状态失败!");
                return false;
            }

            //
            this.ShowNodeData = null;

            return true;
        }
    }
}
